//
//  ECAttributedStringBuilder.swift
//  EasyCoding
//
//  Created by JY_NEW on 2021/8/19.
//

import Foundation

@resultBuilder
public struct ECAttributedStringBuilder {
    public static func buildBlock(_ segments: ECAttributedStringBuildable...) -> ECAttributedStringBuildable {
        return ECAttributedStringBuildItemArray(items: segments)
    }
    public static func buildIf(_ item: ECAttributedStringBuildable?) -> ECAttributedStringBuildable  {
        return item ?? ECAttributedStringBuildItemNone()
    }
    public static func buildEither(first: ECAttributedStringBuildable) -> ECAttributedStringBuildable {
        return first
    }
    public static func buildEither(second: ECAttributedStringBuildable) -> ECAttributedStringBuildable {
        return second
    }
    public static func buildArray(_ components: [ECAttributedStringBuildable]) -> ECAttributedStringBuildable {
        return ECAttributedStringBuildItemArray(items: components)
    }
}


extension EasyCoding where Base: NSAttributedString {
    public static func build(_ attrs: ECStringAttribute..., @ECAttributedStringBuilder builder: () -> ECAttributedStringBuildable) -> NSMutableAttributedString {
        let result = builder()
        if let string = result.__easyPerformBuildString() {
            if string.attributes != nil {
                string.attributes!.insert(contentsOf: attrs, at: 0)
            }else{
                string.attributes = attrs
            }
            return string.attributedString
        }
        return NSMutableAttributedString().easy.attrs(attrs)
    }
}

#if EASY_SHORTCUT

extension NSAttributedString {
    public static func build(_ attrs: ECStringAttribute..., @ECAttributedStringBuilder builder: () -> ECAttributedStringBuildable) -> NSMutableAttributedString {
        let result = builder()
        if let string = result.__easyPerformBuildString() {
            if string.attributes != nil {
                string.attributes!.insert(contentsOf: attrs, at: 0)
            }else{
                string.attributes = attrs
            }
            return string.attributedString
        }
        return NSMutableAttributedString().easy.attrs(attrs)
    }
}

#endif
